//
// Copyright (c) 2014 the ParticleEditor2D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

#include "DialFloatEditor.h"
#include <QDial>
#include <QDoubleSpinBox>
#include <QVBoxLayout>

namespace Urho3D
{

DialFloatEditor::DialFloatEditor(const QString& text) :
    QGroupBox(text),
    scaleFactor_(1.0f),
    lastDialValue_(0)
{
    QVBoxLayout* vBoxLayout = new QVBoxLayout();
    setLayout(vBoxLayout);

    dial_ = new QDial();

    dial_->setWrapping(true);
    dial_->setRange(0, 100);
    connect(dial_, SIGNAL(dialPressed()), this, SLOT(dialPressed()));
    connect(dial_, SIGNAL(valueChanged(int)), this, SLOT(dialValueChanged(int)));

    spinBox_ = new QDoubleSpinBox();
    vBoxLayout->addWidget(spinBox_, 1);
    vBoxLayout->addWidget(dial_);
    spinBox_->setAlignment(Qt::AlignHCenter);
    spinBox_->setButtonSymbols(QDoubleSpinBox::NoButtons);
    connect(spinBox_, SIGNAL(valueChanged(double)), this, SLOT(spinBoxValueChanged(double)));
}

DialFloatEditor::~DialFloatEditor()
{
}

void DialFloatEditor::setValue(float value)
{
    spinBox_->setValue(value);
}

void DialFloatEditor::setRange(float min, float max)
{
    spinBox_->setRange(min, max);

    dial_->setMaximum(100);
    scaleFactor_ = (max - min) / 300.0f;
}

float DialFloatEditor::value() const
{
    return (float)spinBox_->value();
}

void DialFloatEditor::dialPressed()
{
    lastDialValue_ = dial_->value();
}

void DialFloatEditor::dialValueChanged(int value)
{
    int delta = value - lastDialValue_;
    lastDialValue_ = value;

    int range = dial_->maximum();
    if (delta < -range / 2)
        delta += range;
    if (delta > range / 2)
        delta -= range;
    spinBox_->setValue(spinBox_->value() + delta * scaleFactor_);
}

void DialFloatEditor::spinBoxValueChanged(double value)
{
    emit valueChanged((float)value);
}

}